﻿/*******
    * @name bigfileupload-1.0.js
    * @author wy
    * Copyright 2387248
    * 2017年12月22日 
 *******/
var selectcount = 0; //选择文件的次数累计
var select_files = new Array();  //选择文件的列表
var select_files_info = new Array(); //文件信息记录
var record_date = new Date();
var file_name = "";
var input_obj = "";
var seed = 0;   //总数
var all_seed = 0;
var all_total_size = 0; //总文件大小
var shardSize = 2 * 1024 * 1024;		//以?MB为一个分片//大于2M <httpRuntime maxRequestLength="20480"/>kb为单位
var shardCount = 0; //计数
var flag = "0";
var info = "...........";
var fileMD5 = "";
var progressValue = "0"//进度条
var isup = "false" //跟踪是否进行了文件的上传操作
var file_mine = "video/mp4,image/png, image/gif,image/jpeg"; //文件类型设置
var start_time = 0;  //开始时间
var uploadfilesize = 0;//上传字节数
var end_time = 0;    //结束时间
var interval_time = 0; //时间差的毫秒数
var errorcount = 0;//错误次数记录
function changebutton() {
    var btn = document.getElementById("upload");
    var txt = btn.innerText;
    if (txt == "开始上传") {
        btn.innerText = "暂停上传";
        isup = "true";
        var date1 = new Date();
        start_time = date1.getTime();

    } else {
        btn.innerText = "开始上传";
        isup = "false";
        uploadfilesize = 0;
    }
};
     function formatBytes(size) {
        if (size < 100) {
            return (size + 'B');
        } else if (size < 102400) {
            size = Math.round(100 * (size / 1024)) / 100;
            size = isNaN(size) ? 0 : parseFloat(size).toFixed(2);
            return (size + 'K');
        } else if (size < 1047527424) {
            size = Math.round(100 * (size / 1048576)) / 100;
            size = isNaN(size) ? 0 : parseFloat(size).toFixed(2);
            return (size + 'M');
        }

        size = Math.round(100 * (size / 1073741824)) / 100;
        size = isNaN(size) ? 0 : parseFloat(size).toFixed(2);
        return (size + 'G');
    };
    //显示文件进度
    function show(file_index, total_s, size_s, size_total, start_fileContainerid) {
        var o = document.getElementById(start_fileContainerid);
        o.children[2].value = parseFloat(file_index / total_s * 100).toFixed(2);
        o.children[3].innerHTML = parseInt(file_index / total_s * 100)+"%" + "&nbsp;已上传" + formatBytes(size_s)+"，文件大小：" + formatBytes(size_total);
     
    };    //显示文件进度
    function showall(seed, all_seed,size_s,size_total) {
        var ow = document.getElementById("bar");
      
        ow.style.width = ((seed / all_seed) * 200) + 'px'; //200是外框的宽度
        $("#output_percent").text(parseFloat(seed / all_seed * 100).toFixed(2));//显示百分比
        $("#output_All_size").text((formatBytes(size_total)));//显示文件大小
        $("#output_size").text(formatBytes((seed / all_seed) *size_total));//显示上传数据量
     
    };
    //设置选取文件类型，是否多选
    function fileTypeExts(id) {
       
        var file_big_select = document.getElementById(id);
        file_big_select.accept = file_mine;
        file_big_select.multiple = "multiple"; //文件可多选
    };

    function addFile(obj) {  //添加文件
        
        var id = obj.id;
        fileTypeExts(id);//设置选取文件类型
        var add_in = document.getElementById("add_place");
        var file_select = document.getElementById(id);

        var ary = file_select.files.length;
        var content = "";
        var obj = document.getElementById("select_file_list");
        if (ary > 0) {//添加一个Input,
         
        //显示文件列表
            selectcount += 1;
            var file_Inputid = "file_Input_" + selectcount;
            var file_Input = document.createElement("input");
            file_Input.setAttribute("type", "file");
            file_Input.setAttribute("multiple", "multiple");
            file_Input.setAttribute("id", file_Inputid);
            file_Input = file_select;
            obj.appendChild(file_select);
            file_Input.setAttribute("hidden", "hidden"); //隐藏
            var file_Inputid = "file_Input_" + selectcount;
            var file_Input = document.createElement("input");
            file_Input.setAttribute("type", "file");
            file_Input.setAttribute("onchange", "addFile(this)");
            file_Input.setAttribute("multiple", "multiple");
           // file_Input.setAttribute("webkitdirectory", "webkitdirectory");
            file_Input.setAttribute("class", "file_input");
            file_Input.setAttribute("accept", file_mine);
            file_Input.setAttribute("id", file_Inputid);
            add_in.appendChild(file_Input); //添加新的文件选择
        }
        //获取文件列表中文件最大序号，往下累加
        var temp_file_list = document.getElementsByClassName("fileContainer");
        
        var temp_file_id = 0;
        if (temp_file_list.length > 0) {
            var temp_fileContainerID = temp_file_list[temp_file_list.length - 1].id;
            temp_file_id = parseInt(temp_fileContainerID.substring(temp_fileContainerID.lastIndexOf("_") + 1));


        };
        
        for (i = 0; i < ary; i++) {
            var type = file_select.files[i].name.toLowerCase();
            type = type.substr(type.lastIndexOf("."));
            if (type != ".jpg" && type != ".gif" && type != ".jpeg" && type != ".png" && type != ".mp4" && type != ".rar" && type != ".iso" && type != ".zip") {
                //alert("您上传图片的类型不符合(.jpg|.jpeg|.gif|.png|.mp4|.rar)！");
                info += "<li>"+ file_select.files[i].name+"文件类型不支持！" +"</li>"
                var temp_TextArea_file_list0 = document.getElementById("TextArea_file_list0");
                temp_TextArea_file_list0.innerHTML = info;

            } else {
                  temp_file_id += 1;
                if (temp_file_id > 1000) { //文件上传超过1000禁止
                    alert("上传文件数到达上限！");
                    return;
                }
                    //添加一个File容器
                    var fileContainer = document.createElement("div");   //显示容器
                    var fileContainerId = "fileContainer_" + ( temp_file_id);
                    var file_listID = "file_list_" + (temp_file_id);
                   var deleteId = "delete_" + ( temp_file_id);
                   var progressId = "progress_" + ( temp_file_id);
                   var pencentId = "pencent_" + (temp_file_id);

                    fileContainer.setAttribute("id", fileContainerId);
                    fileContainer.setAttribute("class", "fileContainer");

                    obj.appendChild(fileContainer);
                    //添加file,按钮，progress
                    //添加一个文件图标
                   var ico=document.createElement("div");   //显示图标
                   ico.setAttribute("class", "file-uploading-ico");


         
                    var file_progress = document.createElement("progress");   //显示文件名称
                    file_progress.setAttribute("max", "100");
                    file_progress.setAttribute("value", "0");
                    file_progress.setAttribute("id", progressId);
                    file_progress.setAttribute("class", "progress");
                    var file_name_list = document.createElement("div");   //显示文件名称
                    file_name_list.id = file_listID;
                    file_name_list.setAttribute("class", "file_name_list");
                    file_name_list.setAttribute("alt", file_select.files[i].name );
                    file_name_list.innerHTML = file_select.files[i].name ;
                    var del = document.createElement("input");    //删除按钮
                    del.setAttribute("type", "button");
                    del.setAttribute("value", "删除");
                    del.setAttribute("id", deleteId);
                    del.setAttribute("class", "del_button");
                    del.onclick = function () {  //绑定事件，传递当前对象                             
                       deleteInput(this);
                    }
            
                    fileContainer.appendChild(ico);
                    fileContainer.appendChild(file_name_list);
                    fileContainer.appendChild(file_progress);
                    //添加一个百分比
                    var pencent_span = document.createElement("span");   //显示图标
                    pencent_span.setAttribute("class", "pencent_span");
                    pencent_span.setAttribute("id", pencentId);
                    pencent_span.innerHTML = "0%," + "&nbsp;&nbsp;已上传0，文件大小：" + formatBytes(file_select.files[i].size);
                    fileContainer.appendChild(pencent_span);
                    fileContainer.appendChild(del);
                    $("#output").text("已选择" + temp_file_id +"个文件！");
            }
        }
    };
    function deleteInput(obj) {//删除文件
        if (isup == "true")//重新上传文件)
        {
            alert("请先暂停上传！");
        } else
        {

        ischange = "true";
        var id = obj.id;
        var count = id.substr(id.lastIndexOf("_") + 1);
        var deleteObj = document.getElementById(id);
        var fileContainerObj = document.getElementById("fileContainer_" + count);
        var parentObj = document.getElementById("select_file_list");
       // parentObj.removeChild(deleteObj);
        parentObj.removeChild(fileContainerObj);
        //if (isup == "true")//重新上传文件)
        //{
        //    fileUpload()
        //};
        }
    };
    function fileUpload() {

        //获取上传文件列表
        all_total_size = 0;
        all_seed = 0;
        seed = 0;
        select_files = document.getElementsByClassName("fileContainer");
        if (select_files.length < 1) {
            alert('未选择上传文件！');
            $("#output").text("未选择上传文件！");
            var btn = document.getElementById("upload");
            btn.innerText = "开始上传";
            isup = "false";
            return;
        }
        var start_file = "";
        var start_fileContainerid = "";
        if (select_files.length > 0) {
            for (var select_file_index = 0; select_file_index < select_files.length; ++select_file_index) {

                file_name = select_files[select_file_index].children[1].innerHTML;
                //获得文件所在的容器名称
                progressValue = select_files[select_file_index].children[2].value;
                fileContainerid = select_files[select_file_index].id;
                select_files_info[select_file_index] = get_inputobj_name_size(file_name) + "|" + select_files[select_file_index].id + "|" + progressValue + "|" + file_name;

                var fileinfo = select_files_info[select_file_index];
                var input_Obj_temp = document.getElementById(fileinfo.split("|")[0]);
                var file_index_temp = parseInt(fileinfo.split("|")[1]);
                var file = input_Obj_temp.files[file_index_temp];		//文件对象
                var fileContainer_Elementid = fileinfo.split("|")[3]; //文件容器ID
                size = file.size;					//总大小
                all_total_size += size;            //获取
                shardCount = Math.ceil(size / shardSize);	//总片数
                all_seed += shardCount;
                if (progressValue == 100) { seed += shardCount; };
                if (progressValue < 100 && start_fileContainerid == "") {
                    start_file = file;
                    start_fileContainerid = fileContainer_Elementid;
                };
            };
            showall(seed, all_seed, shardSize, all_total_size);//已经上传的片数，片的总数，计算已经上传的数据量（片的数据大小），文件大小
            if (start_fileContainerid == "") {
                $("#output").text("文件上传全部完成！");
                $("#up_time_last").text(" 剩余时间:" + get_time(0));
                var btn = document.getElementById("upload");
                btn.innerText = "开始上传";
                isup = "false";
            }
            else {
                if (isup == "true")//上传文件)
                {
                    uploadfile(start_file, start_fileContainerid); //读取第一个进度不为100的文件

                };

            };
        };
    };

    function get_time(second) {

        var hours = Math.floor(second / (3600 * 1000))
        //计算相差分钟数
        var leave2 = second % (3600 * 1000)        //计算小时数后剩余的毫秒数
        var minutes = Math.floor(leave2 / (60 * 1000))
        //计算相差秒数
        var leave3 = leave2 % (60 * 1000)      //计算分钟数后剩余的毫秒数
        var seconds = Math.round(leave3 / 1000)
        return (hours + " 小时 " + minutes + " 分钟 " + seconds + " 秒");

    };
    function get_inputobj_name_size(file_name) {
        var curent_inputid = "";
        var curent_input = document.getElementById("file_Input_0");
        var input_files = new Array();
        var file_index = 0;
        input_files = document.getElementsByClassName("file_input");
        //返回文件所在的Input
        for (var input_index = 0; input_index < input_files.length; ++input_index) {
            curent_input = input_files[input_index];
            if (curent_input.files.length > 0) {
                for (file_index = 0; file_index < curent_input.files.length; ++file_index) {
                    var temp_div = document.createElement("div");   //显示图标
                    temp_div.innerHTML = curent_input.files[file_index].name; //文本转换成html
                    if (temp_div.innerHTML == file_name) {
                        curent_inputid = curent_input.id;
                        //  return (curent_inputid + "|" + file_index + "|" + curent_input.files[file_index].size);
                        return (curent_inputid + "|" + file_index + "|" + curent_input.files[file_index].size);
                    };
                };
            };
        };

    };
    function uploadfile(file, start_fileContainerid) {
       // file = $("#file_big")[0].files[file_index];	//文件对象
        name = file.name;					//文件名
        size = file.size;					//总大小
        shardCount = Math.ceil(size / shardSize);	//总片数

        //获取文件MD5的值/*** 大文件很慢，只读取第一片****/
        var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
            // file = this.files[0],
            spark = new SparkMD5.ArrayBuffer(),
            fileReader = new FileReader();
        var start = 0, end = ((start + shardSize) >= file.size) ? file.size : start + shardSize;
        fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
        fileReader.onload = function (e) {
            // console.log('read chunk nr', currentChunk + 1, 'of', chunks);
            spark.append(e.target.result); // Append array buffer
            fileMD5 = spark.end();
            //构造一个表单，FormData是HTML5新增的
            var form = new FormData();
            form.append("name", name);
            form.append("file_md5", fileMD5);
            form.append("total", shardCount);	//总片数
            form.append("size", size);	//总片数
            form.append("index", 0);		//当前是第几片

            //Ajax提交
            $.ajax({
                url: "File/md5.aspx",
                type: "POST",
                data: form,
                processData: false,			//很重要，告诉jquery不要对form进行处理
                contentType: false			//很重要，指定为false才能形成正确的Content-Type
            }).done(function (data, status) {
                var msg = data.split("|");
                var slice_index = parseInt(msg[1]);
                seed = seed + slice_index;
                if (msg[0] == "1") {
                    showall(seed, all_seed, shardSize, all_total_size);//已经上传的片数，片的总数，计算已经上传的数据量（片的数据大小），文件大小
                    show(slice_index, slice_index, file.size, file.size, start_fileContainerid);//已经上传的片数，片的总数，计算已经上传的数据量（片的数据大小），文件大小，
                    info = "<br>" + "." + get_CurentTime().substring(11) + " > " + name + "文件已存在！" + "<br>" + info;
                    var temp_TextArea_file_list0 = document.getElementById("TextArea_file_list0");
                    temp_TextArea_file_list0.innerHTML=info;
                    fileUpload();
                } else
                {

                   uploadfile_slice(slice_index, file, name, size, shardCount, start_fileContainerid);
                };
   
                
 
            });
        };
        fileReader.onerror = function () {
            errorcount += 1;
            
           
            if (errorcount < 20) { //20次
                fileUpload();
                 $("#output").text("文件再次尝试读取！");
            } else
            {
                $("#output").text("文件读取出错！");
            };

        };

    };

    function uploadfile_slice(file_slice_index, file, name, size, shardCount, start_fileContainerid) {
        var start = file_slice_index * shardSize,
            end = Math.min(size, start + shardSize);

        //构造一个表单，FormData是HTML5新增的
        var form = new FormData();
        form.append("data", file.slice(start, end));		//slice方法用于切出文件的一部分

        form.append("name", name);
        form.append("total", shardCount);	//总片数
        form.append("size", size);	//总片数
        form.append("index", file_slice_index + 1);		//当前是第几片

        //Ajax提交
        $.ajax({
            url: "File/File.aspx",
            type: "POST",
            data: form,
            processData: false,			//很重要，告诉jquery不要对form进行处理
            contentType: false			//很重要，指定为false才能形成正确的Content-Type
        }).done(function (data, status) {
            ++file_slice_index;
            uploadfilesize += (end - start);//累加已上传字节数
            var msg = data.split("|");
            showall(seed, all_seed, shardSize, all_total_size);//已经上传的片数，片的总数，计算已经上传的数据量（片的数据大小），文件大小
            show(msg[1], msg[2], (msg[1] / msg[2] * msg[3]), msg[3], start_fileContainerid);//已经上传的片数，片的总数，计算已经上传的数据量（片的数据大小），文件大小，
            if (file_slice_index <= shardCount) {
                ++seed;
            }
            if (file_slice_index < shardCount) {
                if (isup == "true")//是否继续上传文件)
                {
                     uploadfile_slice(file_slice_index, file, name, size, shardCount, start_fileContainerid);
                }
            };
            if (file_slice_index % 50 == 1) { info = "." + info; }; //一百兆进一   
            //计算上传速度
            var date2 = new Date();
            end_time = date2.getTime();
            interval_time = end_time - start_time;
            $("#up_speed").text(formatBytes(uploadfilesize / interval_time * 1000) + "/s");
            $("#up_time_last").text(" 剩余时间:" + get_time(((all_seed - seed) * shardSize / (uploadfilesize / interval_time))));
            //显示文件上传信息
            if (msg[0].toLowerCase() == "ok") {
                info = "<br>" + "." + get_CurentTime().substring(11) + " > " + name + "上传完成！" + "<br>" + info;
                 flag = "1";
                fileUpload();
            }
            else if ((msg[0].toLowerCase() == "error")) {
                info += "error";
            }
            var temp_TextArea_file_list0 = document.getElementById("TextArea_file_list0");
            temp_TextArea_file_list0.innerHTML = info;
        }).fail(function (data, status) {
            //  uploadfile(fileindex);
            errorcount += 1;


            if (errorcount < 20) { //20次
                fileUpload();
                $("#output").text("文件再次尝试上传！");
            } else {
                $("#output").text("文件上传出错！");
            };
        });
    };

    function get_CurentTime() {
        var now = new Date();
        var year = now.getFullYear();       //年  
        var month = now.getMonth() + 1;     //月  
        var day = now.getDate();            //日  
        var hh = now.getHours();            //时  
        var mm = now.getMinutes();          //分  
        var ss = now.getSeconds();           //秒  
        var clock = year + "-";
        if (month < 10)
            clock += "0";
        clock += month + "-";
        if (day < 10)
            clock += "0";
        clock += day + " ";
        if (hh < 10)
            clock += "0";
        clock += hh + ":";
        if (mm < 10) clock += '0';
        clock += mm + ":";
        if (ss < 10) clock += '0';
        clock += ss;
        return (clock);
    }  
